<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="内容类型" prop="contentType">
        <el-select v-model="queryParams.contentType" placeholder="请选择类型" clearable>
          <el-option label="活动" value="activity" />
          <el-option label="评论" value="comment" />
          <el-option label="店铺" value="shop" />
        </el-select>
      </el-form-item>
      <el-form-item label="分享者" prop="userNickname">
        <el-input
          v-model="queryParams.userNickname"
          placeholder="请输入分享者昵称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="正常" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:shares:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:shares:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:shares:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:shares:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="sharesList" 
      @selection-change="handleSelectionChange"
      stripe
      border
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="shareId" width="80" />
      <el-table-column label="分享者" align="center" min-width="150">
        <template slot-scope="scope">
          <div style="display: flex; align-items: center;">
            <el-image
              v-if="scope.row.userAvatarUrl"
              :src="scope.row.userAvatarUrl"
              :preview-src-list="[scope.row.userAvatarUrl]"
              style="width: 30px; height: 30px; border-radius: 50%; margin-right: 8px;"
              fit="cover"
            />
            <div>
              <div>{{ scope.row.userNickname }}</div>
              <div style="font-size: 12px; color: #909399;">{{ scope.row.userCity }}</div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="分享标题" align="center" prop="shareTitle" min-width="180" show-overflow-tooltip />
      <el-table-column label="内容类型" align="center" prop="contentType" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.contentType === 'activity'" type="success" size="small">活动</el-tag>
          <el-tag v-else-if="scope.row.contentType === 'comment'" type="primary" size="small">评论</el-tag>
          <el-tag v-else-if="scope.row.contentType === 'shop'" type="warning" size="small">店铺</el-tag>
          <span v-else>{{ scope.row.contentType }}</span>
        </template>
      </el-table-column>
      <el-table-column label="内容标题" align="center" prop="contentTitle" min-width="150" show-overflow-tooltip />
      <el-table-column label="分享图片" align="center" min-width="120">
        <template slot-scope="scope">
          <div v-if="scope.row.imageUrls && formatImageList(scope.row.imageUrls).length > 0" style="display: flex; justify-content: center; gap: 5px;">
            <el-image
              v-for="(img, index) in formatImageList(scope.row.imageUrls).slice(0, 3)"
              :key="index"
              :src="img"
              :preview-src-list="formatImageList(scope.row.imageUrls)"
              style="width: 40px; height: 40px; border-radius: 4px;"
              fit="cover"
            />
            <span v-if="formatImageList(scope.row.imageUrls).length > 3">+{{ formatImageList(scope.row.imageUrls).length - 3 }}</span>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="查看次数" align="center" prop="viewCount" width="100" />
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
            v-hasPermi="['system:shares:edit']"
          />
        </template>
      </el-table-column>
      <el-table-column label="分享时间" align="center" prop="createdAt" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:shares:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:shares:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改分享记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-tabs v-model="activeTab" type="border-card">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="用户ID" prop="userId">
                  <el-input v-model="form.userId" placeholder="请输入用户ID" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="内容类型" prop="contentType">
                  <el-select v-model="form.contentType" placeholder="请选择类型" style="width: 100%">
                    <el-option label="活动" value="activity" />
                    <el-option label="评论" value="comment" />
                    <el-option label="店铺" value="shop" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="分享标题" prop="shareTitle">
                  <el-input v-model="form.shareTitle" placeholder="请输入分享标题" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="内容标题" prop="contentTitle">
                  <el-input v-model="form.contentTitle" placeholder="请输入内容标题" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="内容文本" prop="contentText">
                  <el-input 
                    v-model="form.contentText" 
                    type="textarea"
                    :rows="4"
                    placeholder="请输入内容文本"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="分享图片" prop="imageUrls">
                  <image-upload 
                    v-model="form.imageUrls" 
                    :limit="9"
                    :fileSize="5"
                    :isShowTip="true"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="分享URL" prop="shareUrl">
                  <el-input v-model="form.shareUrl" placeholder="请输入分享链接URL" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="查看次数" prop="viewCount">
                  <el-input-number v-model="form.viewCount" :min="0" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="状态" prop="status">
                  <el-radio-group v-model="form.status">
                    <el-radio :label="1">正常</el-radio>
                    <el-radio :label="0">禁用</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <!-- 用户信息 -->
          <el-tab-pane label="用户信息" name="user">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="用户昵称" prop="userNickname">
                  <el-input v-model="form.userNickname" placeholder="请输入用户昵称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="用户性别" prop="userGender">
                  <el-select v-model="form.userGender" placeholder="请选择性别" style="width: 100%">
                    <el-option label="男" value="男" />
                    <el-option label="女" value="女" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="用户城市" prop="userCity">
                  <el-input v-model="form.userCity" placeholder="请输入用户所在城市" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="用户头像" prop="userAvatarUrl">
                  <image-upload 
                    v-model="form.userAvatarUrl" 
                    :limit="1"
                    :fileSize="2"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <!-- 扩展信息 -->
          <el-tab-pane label="扩展信息" name="extra">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="扩展数据" prop="extraData">
                  <el-input 
                    v-model="form.extraData" 
                    type="textarea"
                    :rows="8"
                    placeholder='请输入JSON格式的扩展数据'
                  />
                  <span class="form-tip">* 请输入合法的JSON格式数据</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listShares, getShares, delShares, addShares, updateShares } from "@/api/system/shares";
import ImageUpload from '@/components/ImageUpload';

export default {
  name: "Shares",
  components: {
    ImageUpload
  },
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      sharesList: [],
      title: "",
      open: false,
      activeTab: 'basic',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        shareTitle: null,
        contentType: null,
        contentTitle: null,
        contentText: null,
        imageUrls: null,
        userNickname: null,
        userGender: null,
        userCity: null,
        userAvatarUrl: null,
        shareUrl: null,
        viewCount: null,
        status: null,
        extraData: null,
        createdAt: null,
        updatedAt: null
      },
      form: {},
      rules: {
        userId: [
          { required: true, message: "分享用户ID不能为空", trigger: "blur" }
        ],
        shareTitle: [
          { required: true, message: "分享标题不能为空", trigger: "blur" }
        ],
        contentType: [
          { required: true, message: "分享内容类型不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    formatImageList(images) {
      if (!images) return [];
      try {
        const imageArray = typeof images === 'string' ? JSON.parse(images) : images;
        return Array.isArray(imageArray) ? imageArray : [];
      } catch (e) {
        return [];
      }
    },
    getList() {
      this.loading = true;
      listShares(this.queryParams).then(response => {
        this.sharesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleStatusChange(row) {
      let text = row.status === 1 ? "启用" : "禁用";
      this.$modal.confirm('确认要"' + text + '"该分享记录吗？').then(() => {
        return updateShares(row);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
        this.getList();
      }).catch(() => {
        row.status = row.status === 0 ? 1 : 0;
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        shareId: null,
        userId: null,
        shareTitle: null,
        contentType: null,
        contentTitle: null,
        contentText: null,
        imageUrls: null,
        userNickname: null,
        userGender: null,
        userCity: null,
        userAvatarUrl: null,
        shareUrl: null,
        viewCount: 0,
        status: 1,
        extraData: null,
        createdAt: null,
        updatedAt: null
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.shareId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset();
      this.activeTab = 'basic';
      this.open = true;
      this.title = "添加分享记录";
    },
    handleUpdate(row) {
      this.reset();
      this.activeTab = 'basic';
      const shareId = row.shareId || this.ids
      getShares(shareId).then(response => {
        this.form = response.data;
        
        // 处理图片字段
        if (this.form.imageUrls) {
          const urls = typeof this.form.imageUrls === 'string' 
            ? JSON.parse(this.form.imageUrls) 
            : this.form.imageUrls;
          this.form.imageUrls = Array.isArray(urls) ? urls.join(',') : urls;
        }
        
        // 处理JSON字段
        if (this.form.extraData && typeof this.form.extraData === 'object') {
          this.form.extraData = JSON.stringify(this.form.extraData, null, 2);
        }
        
        this.open = true;
        this.title = "修改分享记录";
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const submitForm = JSON.parse(JSON.stringify(this.form));
          
          // 处理图片字段
          if (submitForm.imageUrls && typeof submitForm.imageUrls === 'string') {
            const urlArray = submitForm.imageUrls.split(',').filter(url => url.trim());
            submitForm.imageUrls = urlArray.length > 0 ? JSON.stringify(urlArray) : null;
          }
          
          // 处理JSON字段
          if (submitForm.extraData && typeof submitForm.extraData === 'string') {
            try {
              submitForm.extraData = submitForm.extraData.trim() 
                ? JSON.parse(submitForm.extraData) 
                : null;
            } catch (e) {
              this.$modal.msgError("扩展数据JSON格式不正确");
              return;
            }
          }
          
          if (submitForm.shareId != null) {
            updateShares(submitForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addShares(submitForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDelete(row) {
      const shareIds = row.shareId || this.ids;
      this.$modal.confirm('是否确认删除分享记录编号为"' + shareIds + '"的数据项？').then(function() {
        return delShares(shareIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleExport() {
      this.download('system/shares/export', {
        ...this.queryParams
      }, `shares_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.form-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
  margin-top: 4px;
  display: block;
}

::v-deep .el-tabs--border-card {
  box-shadow: none;
}

::v-deep .el-tabs__content {
  padding: 20px;
}
</style>
